/*
 * Copyright © 2018 CODESTD.COM Inc. All rights reserved.
 */
package com.codestd.security.service.impl;

import com.codestd.security.service.AsyncService;
import com.codestd.security.service.NewThreadService;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * TODO
 *
 * @author jaune
 * @since 1.0.0
 */
@Service
public class ThreadServiceImpl implements AsyncService, NewThreadService {

    private static Logger logger = LoggerFactory.getLogger(ThreadServiceImpl.class);

    @Override
    @Async
    public void testGetSubject() {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        logger.info("Service Thread Name:" + Thread.currentThread().getName());
        if (SecurityUtils.getSubject() != null) {
            Object principal = SecurityUtils.getSubject().getPrincipal();
            if (principal != null) {
                logger.info("Service principal: " + principal);
            } else {
                logger.info("无法获取到principal：");
            }
        } else {
            logger.info("无法获取到Subject");
        }
    }

    public void newThreadTest() {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                logger.info("New Thread Name:" + Thread.currentThread().getName());
                if (SecurityUtils.getSubject() != null) {
                    Object principal = SecurityUtils.getSubject().getPrincipal();
                    if (principal != null) {
                        logger.info("new Thread principal: " + principal);
                    } else {
                        logger.info("无法获取到principal：");
                    }
                } else {
                    logger.info("无法获取到Subject");
                }
            }
        }).start();
    }
}
